<template>
  <div class="app-container" style="padding:0">

    <div class="topLine">
      <!-- 搜索 -->
      <el-form ref="queryForm" :model="listQuery" :inline="true" label-width="68px">
        <el-form-item label="任务名称">
          <el-input
            v-model="listQuery.task_name"
            placeholder="请输入任务名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增 </el-button>
        <!-- <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除 </el-button> -->
      </div>

    </div>

    <el-table v-loading="loading" :data="list" empty-text="暂无数据" @selection-change="handleSelectionChange">i
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column label="任务名称" align="center">
        <template slot-scope="scope">
          <div class="nameLine">
            {{ scope.row.task_name }}<div v-if="scope.row.default_type === 1" class="defaultTag">默认</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="模板名称" align="center" prop="template_name" :show-overflow-tooltip="true" />
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="重复" align="center" prop="cycle_type">
        <template #default="{ row }">
          {{ { once: '一次', daily: '每天', weekly: '自定义' }[row.cycle_type] || row.cycle_type }}
        </template>
      </el-table-column>


      <el-table-column label="开始时间" align="center" prop="start_time" />
      <el-table-column label="结束时间" align="center" prop="end_time" />

      <!-- <el-table-column label="创建时间" align="center" prop="create_time" :show-overflow-tooltip="true">
        <template slot-scope="scope">{{ scope.row.create_time }}</template>
      </el-table-column> -->

      <el-table-column label="激活" align="center" prop="is_active">
        <template #default="{ row }">
          <span :class="{ 'active-text': row.is_active, 'inactive-text': !row.is_active }">
            {{ row.is_active ? '已激活' : '未激活' }}
          </span>
        </template>
      </el-table-column>



      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getSchedule"
    />

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="模板" prop="params_start.template_id">
          <el-select v-model="form.params_start.template_id" placeholder="请选择" clearable style="width:356px">
            <el-option
              v-for="item in templateST"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              @click.native="changeSelect(item)"
            />
          </el-select>
          <el-tooltip v-if="currentTemplate.description" class="item" effect="light" :content="currentTemplate.description" placement="top">
            <i class="el-icon-warning-outline" style="font-size:22px;margin-left:4px;color:#1890ff" />
          </el-tooltip>
          <i v-else class="el-icon-warning-outline" style="font-size:22px;margin-left:4px;color:#dcdfe6" />
        </el-form-item>


        <el-form-item label="任务名称" prop="task_name">
          <el-input v-model="form.task_name" placeholder="请输入任务名称" />
        </el-form-item>

        <el-form-item label="重复规则" prop="cycle_type">          
          <el-select v-model="form.cycle_type" placeholder="请选择" clearable style="width:356px">
            <el-option
              v-for="item in repeatRule"
              :key="item.value"
              :label="item.name"
              :value="item.value"           
            />
          </el-select>        
        </el-form-item>
        
        <el-form-item v-if="form.cycle_type === 'weekly' " label="自定义日期" prop="week_days"> 
          <el-checkbox-group v-model="form.week_days">
            <el-checkbox label="0">周一</el-checkbox>
            <el-checkbox label="1">周二</el-checkbox>
            <el-checkbox label="2">周三</el-checkbox>
            <el-checkbox label="3">周四</el-checkbox>
            <el-checkbox label="4">周五</el-checkbox>
            <el-checkbox label="5">周六</el-checkbox>
            <el-checkbox label="6">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item v-if="form.cycle_type === 'once' " label="日期选择" prop="date">
          <el-date-picker v-model="form.date" type="date" placeholder="选择日期" :picker-options="datePickerOptions" style="width:356px" />
        </el-form-item>

        <el-form-item label="时间范围">
          <div style="display: inline-flex; align-items: center; width: 100%;">   
            <el-time-picker
              v-model="form.time1"
              placeholder="开始时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width:356px"
            />
            <span style="padding: 0 10px">-</span>
            <el-time-picker
              v-model="form.time2"
              placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width:356px"
            />        
          </div>
        </el-form-item>


        <el-form-item label="任务描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="激活">
          <el-switch v-model="form.is_active" active-color="#1890ff" inactive-color="#ff4949" />
        </el-form-item>

      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
// 接口
import { getTemplates, getScheduleByPage, getScheduleDetail, updateTaskDetail, addSchedule , deleteTask, getTemplateDetail } from '@/api/main'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import dayjs from "dayjs";

export default {
  name: 'TemplateMain',
  components: {  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      listQuery: {
        page: 1,
        limit: 10,
        task_name: undefined,
        type: 1
      },
      form: {
        params_start: {  
          template_id: "",  
        },
      },
      datePickerOptions: {
        disabledDate(time) {
          // 禁用今天及之前的日期
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      // 表单校验
      rules: { 
        "params_start.template_id": [
          { required: true, message: '请选择模板', trigger: 'blur' }
        ],
        task_name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        date: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.cycle_type === "once" && !value) {
                callback(new Error("请选择日期"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        cycle_type: [
          { required: true, message: '请选择重复规则', trigger: 'change' }
        ],
        week_days: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.cycle_type === "weekly" && value.length === 0) {
                callback(new Error("请至少选择一个星期"));
              } else {
                callback();
              }
            },
            trigger: "change" 
          }
        ],
      },
      currentTemplate: {},
      repeatRule: [
        {name: '一次', value: 'once'},
        {name: '每天', value: 'daily'},
        {name: '自定义', value: 'weekly'}
      ],
      templateValue: '',
    //  repeatValue:'',
      templateST: [], // ST模板
      disabledHours: [],  // 禁用的小时
      disabledMinutes: [],  // 禁用的分钟
      disabledSeconds: [],  // 禁用的秒

    }
  },
  watch: { },
  created() {
    // 获取定时任务-分页
    this.getSchedule()
    // 获取模板
    this.getAllTemplates()
  },
  methods: {

    // 获取模板
    getAllTemplates() {
      getTemplates().then(response => {
        this.templateST = response.data.filter(item =>
          item.type === 1
        )
      })
    },

    // 选择模板
    changeSelect(val) {
      this.currentTemplate = val
    },

// 获取定时任务
async getSchedule() {
  this.loading = true;
  try {
    const response = await getScheduleByPage(this.listQuery);
    
    // 使用Promise.all处理所有任务的模板请求
    const tasksWithTemplate = await Promise.all(
      response.data.tasks_data.map(async (item) => {
        // 基础数据处理
        const formattedItem = {
          ...item,
          start_time: item.cycle_type === "once" 
            ? dayjs(item.start_time).format("YYYY-MM-DD HH:mm:ss")
            : dayjs(item.start_time).format("HH:mm:ss"),
          end_time: item.cycle_type === "once" 
            ? dayjs(item.end_time).format("YYYY-MM-DD HH:mm:ss")
            : dayjs(item.end_time).format("HH:mm:ss"),
          template_name: '' // 先初始化
        };
        
        // 如果有template_id，则获取模板名称
        if (item.params_start && item.params_start.template_id) {
          try {
            const templateRes = await getTemplateDetail(item.params_start.template_id);
            formattedItem.template_name = (templateRes.data.template_data && templateRes.data.template_data.name) || '未知模板';
          } catch (error) {
            console.error(`获取模板${item.params_start.template_id}失败:`, error);
          }
        }
        
        return formattedItem;
      })
    );
    
    this.list = tasksWithTemplate;
    this.total = response.data.total;
  } catch (error) {
    console.error('获取任务列表失败:', error);
  } finally {
    this.loading = false;
  }
},

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        task_name: undefined, 
        description: undefined,
        start_time: undefined,
        end_time: undefined,
        cycle_type: 'once',
        is_active: true,
        week_days: [],
        params_start: {
          "template_id": ''
        },
      }
      // this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.listQuery.page = 1
      this.getSchedule()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        type: 1
      }
      this.handleQuery()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增定时任务'
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 提取HH:mm的公共方法
    extractTime(isoString) {
      if (!isoString) return '';
      const match = isoString.match(/\d{2}:\d{2}(?=:\d{2})/);
      return match ? match[0] : '';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getScheduleDetail(id).then(response => {
        this.open = true
        this.title = '修改定时任务' 
        this.form =  {
          ...response.data, // 展开API返回的所有字段
          date: response.data.cycle_type === 'once' 
            ? response.data.start_time.split('T')[0] 
            : null,
          time1: this.extractTime(response.data.start_time),
          time2: this.extractTime(response.data.end_time),
          // 转换week_days数字数组为字符串数组（因为checkbox label是字符串）
          week_days: response.data.week_days 
            ? response.data.week_days.map(String) // 将数字转为字符串
            : []
        }

      })
    },

  // 提交时处理
  formatSubmitData() {
    // 检查必填字段
    if (!this.form.time1 || !this.form.time2) {
      this.$message.error("请选择开始和结束时间！");
      return null;
    }

    // 处理时间格式
    const dateStr = this.form.cycle_type === 'once' 
      ? dayjs(this.form.date).format("YYYY-MM-DD")  // 单次任务：使用选择的日期
      : dayjs().format("YYYY-MM-DD");               // 其他任务：使用当天日期

    const start_time = `${dateStr} ${this.form.time1}`;
    const end_time = `${dateStr} ${this.form.time2}`;

    // 转换 week_days 为数字数组（如果是每周任务）
    const week_days = this.form.cycle_type === "weekly" 
      ? this.form.week_days.map(Number) 
      : undefined;

    return {
      id: this.form.id, // 修改时使用已有的id，新增时为undefined
      task_name: this.form.task_name, 
      params_start: {  
        template_id: (this.form.params_start && this.form.params_start.template_id) || ''  
      },
      description: this.form.description,
      start_time: start_time,
      end_time: end_time,
      cycle_type: this.form.cycle_type,
      week_days: week_days,
      is_active: this.form.is_active,
    };
  },
   // 提交表单
   submitForm(formName) {
    this.$refs[formName].validate((valid) => {
      if (!valid) {
        console.log('error submit!!');
        return false;
      }

      // 格式化提交数据
      const post = this.formatSubmitData();
      if (!post) return; // 如果返回null，说明有错误
    

      if (this.form.id === undefined) {
        // 新增
        addSchedule(post).then(response => {
          if (response.code === 20000) {
            this.msgSuccess(response.message);
            this.open = false;
            this.getSchedule();
          }
        });
      } else {
        // 修改
        updateTaskDetail(post).then(response => {
          if (response.code === 20000) {
            this.msgSuccess(response.message);
            this.open = false;
            this.getSchedule();
          } else {
            this.msgSuccess(response.message);
          }
        });
      }
    });
  },



    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return deleteTask(ids)
      }).then(() => {
        this.getSchedule()
        this.msgSuccess('删除成功---')
      }).catch(function() {
      })
    },

    handleStartTimeChange(startTime) {
      if (!startTime) {
        // 如果开始时间为空，不清除禁用逻辑
        return;
      }

      const startHour = startTime.getHours();
      const startMinute = startTime.getMinutes();
      const startSecond = startTime.getSeconds();

      // 禁用比开始时间早的小时
      this.disabledHours = () => {
        const hours = [];
        for (let i = 0; i < startHour; i++) {
          hours.push(i);
        }
        return hours;
      };


      // 如果结束时间的小时和开始时间相同，则禁用比开始时间早的分钟
      this.disabledMinutes = (hour) => {
        if (hour === startHour) {
          const minutes = [];
          for (let i = 0; i < startMinute; i++) {
            minutes.push(i);
          }
          return minutes;
        }
        return [];
      };

      // 如果结束时间的分钟和开始时间相同，则禁用比开始时间早的秒
      this.disabledSeconds = (hour, minute) => {
        if (hour === startHour && minute === startMinute) {
          const seconds = [];
          for (let i = 0; i < startSecond; i++) {
            seconds.push(i);
          }
          return seconds;
        }
        return [];
      };
    },


  }
}
</script>

<style>
.topLine{
  padding:20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
}
.el-table .el-table__header-wrapper th{
  background: #e1ecfa;
}
.topLine .el-form-item{
  margin-bottom: 0;
}
.nameLine{
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.defaultTag{
  color: #385eb7;
  font-size: 11px;
  line-height: 18px;
    padding: 0px 6px;
    border: 1px dashed #b2c6e0;
    margin-left: 8px;
    border-radius: 5px;
    background: rgba(231.9, 243.9, 255, 0.4);
}
.active-text{
  color: #385eb7;
}
.inactive-text{
  color: #d64242;
}
</style>
